<?php
if ($_POST) {
    include_once("../../Functions/connectDatabase.php");
    get_connection();
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["newName"])) {
            echo "<script>alert('修改后的新闻类别名称不能为空！');
        window.location.href='./Modify_V.php'
        </script>";
        } else {
            $newName = $_POST["newName"];
            $oldName = $_POST["oldName"];
            $id = $_POST["id"];
            if ($newName == $oldName) {
                echo "<script>alert('修改后的名称与修改前相同！');window.location.href='./adminShow.php'</script>";
            } else {
                $sql = "SELECT * FROM category WHERE category_name='$newName'";
                $result = mysqli_query($conn, $sql);
                if ($result->num_rows == 0) {
                    $sql = "UPDATE category SET category_name='$newName' WHERE category_id='$id'";
                    if (mysqli_query($conn, $sql)) {
                        echo "<script>alert('修改成功！');window.location.href='./adminShow.php'</script>";
                    } else {
                        $error = mysqli_error($conn);
                        $error = str_replace('\'', '', $error);
                        echo "<script>alert('修改失败！$error');</script>";
                    }
                } else {
                    echo "<script>alert('修改失败！已存在相同名称的新闻类型！');window.location.href='./adminShow.php'</script>";
                }
            }
        }
    }
    close_connection();
}
?>